package common.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public abstract class ObjectProxy implements InvocationHandler {
	protected Object realObj; //真实的对象
	protected Object proxyObj; //代理的对象
	protected String[] proxyMethod;//代理的方法
	
	//构造方法：需要将真实的对象传入
	public ObjectProxy(Object realObj) {
		this.realObj = realObj;
	}
	
	//获取代理对象
	public Object getProxyObj() {
		createProxyObj();
		return proxyObj;
	}
	
	//获取真实的对象
	public Object getRealObj() {
		return this.realObj;
	}
	
	//创建代理对象
	@SuppressWarnings("unchecked")
	private void createProxyObj() {
		Class[] interfaces = realObj.getClass().getInterfaces();
		if (interfaces == null || interfaces.length == 0) {
			interfaces = new Class[1];
			interfaces[0] = this.getInterfaceClass();
		}
		this.proxyObj = Proxy.newProxyInstance(realObj
						.getClass().getClassLoader(), interfaces, this);

	}
	
	protected Class<? extends Object> getInterfaceClass() {
		return realObj.getClass();
	}

	//实现接口
	public abstract Object invoke(Object proxy, Method method, Object[] args) throws Throwable;
	
	 /**
	  * 检查方法是否需要代理
	  * @param methodName
	  * @return
	  */
    protected boolean isProxyMethod(String methodName) {
        if (proxyMethod == null || proxyMethod.length == 0) {
            return false;
        }
          
        for(int i=0;i<proxyMethod.length;i++){
        	if(methodName.equals(proxyMethod[i])){
        		return true;
        	}
        }
        return false;
    }
}
